package com.ruoyi.system.service.impl;

import com.ruoyi.common.core.utils.MD5Utils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.redis.service.RedisService;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.system.domain.SysOrganizationDomain;
import com.ruoyi.system.domain.SysOrganizationDomainChildren;
import com.ruoyi.system.domain.SysOrganizationDomainLabel;
import com.ruoyi.system.domain.dto.SysOrganizationDomainDto;
import com.ruoyi.system.domain.vo.SysOrganizationDomainVo;
import com.ruoyi.system.mapper.SysOrganizationDomainMapper;
import com.ruoyi.system.service.ISysOrganizationDomainService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 组织领域Service业务层处理
 *
 * @author ruoyi
 * @date 2024-08-29
 */
@Service
public class SysOrganizationDomainServiceImpl implements ISysOrganizationDomainService {
    @Autowired
    private SysOrganizationDomainMapper sysOrganizationDomainMapper;

    @Autowired
    private RedisService redisService;

    /**
     * 查询组织领域
     *
     * @param id 组织领域主键
     * @return 组织领域
     */
    @Override
    public SysOrganizationDomain selectSysOrganizationDomainById(String id) {
        // 查询该节点
        SysOrganizationDomain node = sysOrganizationDomainMapper.selectSysOrganizationDomainById(id);

        // 递归查询并设置子节点
        if (node != null) {
            List<SysOrganizationDomain> children = getChildrenByParentId(node.getId());
            node.setChildren(children);
        }

        return node;

//        return sysOrganizationDomainMapper.selectSysOrganizationDomainById(id);
    }

    // 递归查询子节点
    private List<SysOrganizationDomain> getChildrenByParentId(String parentId) {
        // 查询该父节点的所有子节点
        List<SysOrganizationDomain> children = sysOrganizationDomainMapper.selectChildrenByParentId(parentId);

        // 对每个子节点，递归查询其子节点
        for (SysOrganizationDomain child : children) {
            List<SysOrganizationDomain> grandChildren = getChildrenByParentId(child.getId());
            child.setChildren(grandChildren);
        }

        return children;
    }

    /**
     * 查询组织领域列表
     *
     * @param sysOrganizationDomain 组织领域
     * @return 组织领域
     */
    public List<SysOrganizationDomain> selectSysOrganizationDomainList(SysOrganizationDomainDto sysOrganizationDomain) {
        SysOrganizationDomain pojo = new SysOrganizationDomain();
        BeanUtils.copyProperties(sysOrganizationDomain, pojo);

        // 如果 category 是 2，则进行深度控制，查询到第四级别
        if ("2".equals(pojo.getCategory())) {
            return buildTreeFromDatabase2(pojo, 4); // 限制查询深度为 4 级
        }
        if ("3".equals(pojo.getCategory())) {
            return buildTreeFromDatabase2(pojo, 3); // 限制查询深度为 4 级
        }
        return buildTreeFromDatabase2(pojo,5); // 如果没有设置 category，返回完整结构
    }

    // 递归方法，支持深度控制
    private List<SysOrganizationDomain> buildTreeFromDatabase2(SysOrganizationDomain sysOrganizationDomain, int depth) {
        // 如果达到最大深度，则停止递归
        if (depth <= 0) {
            return Collections.emptyList();
        }

        sysOrganizationDomain.setCreateUser(SecurityUtils.getUsername());
        sysOrganizationDomain.setUserId(SecurityUtils.getUserId());

        // 查询当前层级的节点（直接子节点）
        List<SysOrganizationDomain> currentNodes = new ArrayList<>();

/*
        String redisKey = "selectSysOrganizationDomainList" + sysOrganizationDomain.getParentId() + sysOrganizationDomain.getCategory() + SecurityUtils.getUsername();
        // 1. 尝试从Redis获取缓存数据
        currentNodes = redisService.getCacheObject(redisKey);
*/

        // 2. 如果Redis中没有缓存数据，则从数据库查询
        if (currentNodes == null || currentNodes.isEmpty()) {
            currentNodes = sysOrganizationDomainMapper.selectSysOrganizationDomainList(sysOrganizationDomain);

            // 3. 将查询结果存入Redis，设置缓存时间（例如30分钟）
//            redisService.setCacheObject(redisKey, currentNodes, 30L, TimeUnit.MINUTES);
        }


        // 如果没有子节点，直接返回空列表
        if (currentNodes == null || currentNodes.isEmpty()) {
            return Collections.emptyList();
        }

        // 对每个节点递归查询其子节点（儿子节点）
        for (SysOrganizationDomain node : currentNodes) {
            SysOrganizationDomain queryForChildren = new SysOrganizationDomain();
            queryForChildren.setParentId(node.getId());

            // 获取当前节点的直接子节点（儿子）
            List<SysOrganizationDomain> children = buildTreeFromDatabase2(queryForChildren, depth - 1); // 深度递减

            // 将儿子节点设置为当前节点的 children
            node.setChildren(children);
        }

        return currentNodes; // 返回当前节点及其子树
    }


    /**
     * 新增组织领域
     *
     * @param sysOrganizationDomain 组织领域
     * @return 结果
     */
    @Override
    public int insertSysOrganizationDomain(SysOrganizationDomain sysOrganizationDomain) {
        sysOrganizationDomain.setCreateUser(SecurityUtils.getUsername());
        sysOrganizationDomain.setCreatedAt(new Date());

//        + sysOrganizationDomain.getParentId()
        sysOrganizationDomain.setId(MD5Utils.md5(sysOrganizationDomain.getLabel()));

        return sysOrganizationDomainMapper.insertSysOrganizationDomain(sysOrganizationDomain);
/*        if ("4".equalsIgnoreCase(sysOrganizationDomain.getCategory())) {

        }
        if (StringUtils.isNotEmpty(sysOrganizationDomain.getParentId())) {
            return sysOrganizationDomainMapper.updateSysOrganizationDomain(sysOrganizationDomain);
        } else {
            return sysOrganizationDomainMapper.insertSysOrganizationDomain(sysOrganizationDomain);
        }*/

    }

    /**
     * 修改组织领域
     *
     * @param sysOrganizationDomain 组织领域
     * @return 结果
     */
    @Override
    public int updateSysOrganizationDomain(SysOrganizationDomain sysOrganizationDomain) {


        int updateResult = sysOrganizationDomainMapper.updateSysOrganizationDomain(sysOrganizationDomain);

        if (0 == updateResult) {
            updateResult = this.insertSysOrganizationDomain(sysOrganizationDomain);
        }

        return updateResult;

    }

    /**
     * 批量删除组织领域
     *
     * @param ids 需要删除的组织领域主键
     * @return 结果
     */
    @Override
    public int deleteSysOrganizationDomainByIds(String[] ids) {

        sysOrganizationDomainMapper.deleteSysOrganizationDomainRefByIds(ids);

        return sysOrganizationDomainMapper.deleteSysOrganizationDomainByIds(ids);
    }

    /**
     * 删除组织领域信息
     *
     * @param id 组织领域主键
     * @return 结果
     */
    @Override
    public int deleteSysOrganizationDomainById(String id) {
        return sysOrganizationDomainMapper.deleteSysOrganizationDomainById(id);
    }

    @Override
    public List<SysOrganizationDomainVo> queryDomainList(SysOrganizationDomainDto sysOrganizationDomain) {
        String redisKey = "queryDomainList" + sysOrganizationDomain.getParentId() + sysOrganizationDomain.getCategory() + SecurityUtils.getUsername();

        // 1. 尝试从Redis获取缓存数据
        List<SysOrganizationDomainVo> domainList = redisService.getCacheObject(redisKey);

        // 2. 如果Redis中没有缓存数据，则从数据库查询
        if (domainList == null || domainList.isEmpty()) {
            domainList = sysOrganizationDomainMapper.queryDomainList(sysOrganizationDomain);

            // 3. 将查询结果存入Redis，设置缓存时间（例如30分钟）
            redisService.setCacheObject(redisKey, domainList, 30L, TimeUnit.MINUTES);
        }

        // 4. 返回结果
        return domainList;
    }

    @Override
    public int addChildren(SysOrganizationDomainChildren sysOrganizationDomainChildren) {
        SysOrganizationDomain domain = new SysOrganizationDomain();
        BeanUtils.copyProperties(sysOrganizationDomainChildren, domain);

        int result = this.insertSysOrganizationDomain(domain);

//        增加孩子前 先删除旧关联
//        sysOrganizationDomainMapper.deleteByParentId(domain.getId());

/*        if(children !=null  ){
            for(SysOrganizationDomainChildren child : children){
                child.setParentId( domain.getId());
                SysOrganizationDomain childDomain= new SysOrganizationDomain();
                BeanUtils.copyProperties( child , childDomain );
                if("3".equalsIgnoreCase( domain.getCategory())){
                    childDomain.setCategory("4");
                }
                if("2".equalsIgnoreCase( domain.getCategory())){
                    childDomain.setCategory("3");
                }
                if("1".equalsIgnoreCase( domain.getCategory())){
                    childDomain.setCategory("2");
                }
                this.insertSysOrganizationDomain(childDomain ) ;
//                sysOrganizationDomainMapper.updateParentId(child);
                childDomain =null;
            }

        }*/
//        sysOrganizationDomainMapper.insertChildren(children)
        return result;
    }

    @Override
    public List<SysOrganizationDomainLabel> queryDomainLabelList(SysOrganizationDomainDto sysOrganizationDomain) {
        sysOrganizationDomain.setCreateUser(SecurityUtils.getUsername());
        return sysOrganizationDomainMapper.queryDomainLabelList(sysOrganizationDomain);
    }


}
